package socket2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/*
聊天室服务端
 */
public class Server {


    public static void main(String[] args) {

        Runnable r1 =new Chat1();
        Runnable r2 =new Chat2();
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);

        t1.start();
        t2.start();
    }
}
class Chat1 implements Runnable{
    private ServerSocket serverSocket1; //创建服务器serverSocket
    public  void run (){
            try {
                serverSocket1 = new ServerSocket(8088);
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {

                System.out.println("等待客户端连接");
                Socket socket = serverSocket1.accept();
                System.out.println("第一个客户连接");


                //通过SOCKET获取输入流对方输入的消息

                InputStream in =socket.getInputStream();

                InputStreamReader isr =new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br =new BufferedReader(isr);
                String line;
                while((line = br.readLine())!=null) {
                    System.out.println("第一个客户说"+line);
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
class Chat2 implements Runnable {
    private ServerSocket serverSocket2;

    public void run() {
        try {
            System.out.println("等待客户端连接");
            serverSocket2 = new ServerSocket(8089);


            System.out.println("一个客户端连接");


            //通过SOCKET获取输入流对方输入的消息

            //InputStream in = serverSocket2.getInputStream();
            Socket socket = serverSocket2.accept();
            InputStream in =socket.getInputStream();

            InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("第二个客户说" + line);
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
